package java_thinking.unit_14._14_3;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description : 使用isAssignableFrom()来执行运行时检查，校验传递的对象是所需继承结构
 * @author: cww
 * @DateTime: 2019-03-29 23:00
 */

public class TypeCounter extends HashMap<Class<?>,Integer> {
    private Class<?> baseType;
    public TypeCounter(Class<?> baseType){
        this.baseType = baseType;
    }
    public void count(Object obj) {
        Class<?> type = obj.getClass();
        if (!baseType.isAssignableFrom(type)){
            throw new RuntimeException(obj + "incorrect type: "
                    + type +",should be type or subtype of "+baseType);
        }
        countClass(type);
    }
    private void countClass(Class<?> type) {
        Integer quantity = get(type);
        put(type,quantity == null?1:quantity+1);
        Class<?> superClass = type.getSuperclass();
        if (superClass !=null && baseType.isAssignableFrom(superClass)){
            countClass(superClass);
        }
    }
    @Override
    public String toString() {
        StringBuilder result = new StringBuilder("{");
        for (Map.Entry<Class<?>,Integer> pair : entrySet()){
            result.append(pair.getKey().getSimpleName());
            result.append("=");
            result.append(pair.getValue());
            result.append(", ");
        }
        result.delete(result.length()-2,result.length());
        result.append("}");
        return result.toString();
    }
}
